package ebj.common.JDBC.conn_pool.custom;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Hashtable;
/**
 * 连接管理类
 * @author Ran
 *
 */
public class IPoolManager {
	
	
	// 连接池存放
	public Hashtable<String, IPool> pools = new Hashtable<String, IPool>();
	
	// 初始化
	private IPoolManager(){
		init();
	}
	// 单例实现
	public static IPoolManager getInstance(){
		return Singtonle.instance;
	}
	private static class Singtonle {
		private static IPoolManager instance =  new IPoolManager();
	}
	
	
	// 初始化所有的连接池
	public void init(){
		for(int i =0;i< IPoolInit.beans.size();i++){
		    IPoolConfiguration bean = IPoolInit.beans.get(i);
			ConnectionPool pool = new ConnectionPool(bean);
			if(pool != null){
				pools.put(bean.getPoolName(), pool);
				System.out.println("Info: Pool [" +bean.getPoolName() + "] init Succeed.");
			}
		}
	}
	
	// 获得连接,根据连接池名字 获得连接
	public Connection  getConnection(String poolName){
		Connection conn = null;
		if(pools.size()>0 && pools.containsKey(poolName)){
			conn = getPool(poolName).getConnection();
		}else{
			System.out.println("Error:Can't find this connecion pool ->"+poolName);
		}
		return conn;
	}
	
	// 关闭，回收连接
	public void close(String poolName,Connection conn){
			IPool pool = getPool(poolName);
			try {
				if(pool != null){
					pool.releaseConn(conn);
				}
			} catch (SQLException e) {
				System.out.println("连接池已经销毁");
				e.printStackTrace();
			}
	}
	
	// 清空连接池
	public void destroy(String poolName){
	    IPool pool = getPool(poolName);
		if(pool != null){
			pool.destroy();
		}
	}
	
	// 获得连接池
	public IPool getPool(String poolName){
	    IPool pool = null;
		if(pools.size() > 0){
			 pool = pools.get(poolName);
		}
		return pool;
	}
}
